package com.xunyin.dianping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xunyin.enums.CouponTypeEnum;
import com.xunyin.enums.StatusEnum;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.service.UserCouponService;
import com.xunyin.modules.couponnew.service.mapper.MtCouponMapper;
import com.xunyin.modules.mtdianpinggroup.domain.MtDianpingGroup;
import com.xunyin.modules.mtdianpinggroup.service.MtDianpingGroupService;
import com.xunyin.modules.mtdianpinggroup.service.mapper.MtDianpingGroupMapper;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.mtstore.service.mapper.MtStoreMapper;
import com.xunyin.utils.DateUtil;
import com.xunyin.utils.RedisUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 美团点评团购券相关接口
 * <p>
 * Created by xunyin
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DianpingCouponServiceImpl implements DianpingCouponService {

    @Value("${dianping.url}")
    private String dianpingUrl;

    @Value("${dianping.appkey}")
    private String dianpingAppkey;

    @Value("${dianping.secret}")
    private String dianpingSecret;

    @Value("${dianping.callBackUrl}")
    private String callBackUrl;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private StoreService storeService;

    @Autowired
    private MtDianpingGroupService mtDianpingGroupService;

    @Autowired
    private MtDianpingGroupMapper mtDianpingGroupMapper;

    @Autowired
    private MtCouponMapper mtCouponMapper;

    @Autowired
    private UserCouponService userCouponService;

    @Autowired
    private MtStoreMapper mtStoreMapper;

    // session：aa0fe54cd7fb80b016a23b0fe7651de4d85d93ce
    // refresh_session：64d3ae616c886a4ef28c8c2aee3652023b50831f
    // open_shop_uuid：03353631c0d0d08b4679ff097e6b7df2
    // Appkey：d5bdf4fcf1ae2bb0
    // Secret：72ff33fae07ffe3786574ec77e537013e22af309
    // 店铺名称：北极星团购测试33号()

    // 根据authCode,token获取
    @SneakyThrows
    @Override
    public void getToken(Integer storeId) {
        //redisUtils.set(AppConstants.SHOP_REQUESTID,0);
        // 根据门店Id,获取门店对应的appKey、appSecret,默认为配置
        MtStore mtStore = storeService.queryStoreById(storeId);
        if (mtStore != null) {
            //dianpingAppkey = mtStore.getDianpingAppkey();
            //dianpingSecret = mtStore.getDianpingSecret();
            String appkey = mtStore.getDianpingAppkey();
            String secret = mtStore.getDianpingSecret();
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", appkey);
            requestParam.put("app_secret", secret);
            requestParam.put("auth_code", mtStore.getAuthCode());
            requestParam.put("grant_type", "authorization_code");
            requestParam.put("redirect_url", callBackUrl);
            // 回调地址类似支付实现方式,回调地址当获取到authCode后，调用getToken获取token
            // 构造form
            Form form = Form.form();
            for (Map.Entry<String, String> entry : requestParam.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }

            String str = Request.Post(dianpingUrl + "/router/oauth/token").bodyForm(form.build())
                    .setHeader("Content-Type",
                            ContentType.create("application/x-www-form-urlencoded", "UTF-8").toString()).execute().returnContent().asString();
            log.info("dianping_getToken_str:" + str);
            // dianping_getToken_str:{"code":200,"msg":"success","access_token":"c634fe219e727340622b0b565087749b47eacaee","expires_in":2591999,"remain_refresh_count":12,"tokenType":"bearer","scope":"tuangou","bid":"56cc880d44ab4f2b98173810642a763c","refresh_token":"ad16da643ebb1702f884134c3cf2ae07c757446b"}
            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            if (code == 200) {
                // redis 保存token,现在时间加上多少秒之后过期
                // DateUtil.addDate(new Date(), Calendar.DATE,couponInfo.getLimitDay())
                Long expiresIn = jsonStr.getLongValue("expires_in");
                String accessToken = jsonStr.getString("access_token");
                Date endDate = DateUtil.addDate(new Date(), Calendar.SECOND, expiresIn.intValue());
                String refreshToken = jsonStr.getString("refresh_token");
                String bid = jsonStr.getString("bid");
                DianpingTokenResult dianpingTokenResult = new DianpingTokenResult();
                dianpingTokenResult.setAccessToken(accessToken);
                dianpingTokenResult.setEndDate(endDate);
                dianpingTokenResult.setStoreId(storeId);
                dianpingTokenResult.setRefreshToken(refreshToken);
                dianpingTokenResult.setDianpingAppkey(appkey);
                dianpingTokenResult.setDianpingSecret(secret);
                //dianpingTokenResult.setOpenShopUuid(mtStore.getOpenShopUuid());
                dianpingTokenResult.setBid(bid);
                redisUtils.set(AppConstants.SHOP_TOKEN_INFOR + storeId, dianpingTokenResult);
                // session适用店铺查询接口
                sessionScopeShop(storeId);
                // 0表示不需要重新授权
                redisUtils.set(AppConstants.SHOP_TOKEN_AUTH + storeId, 0);

            }
        }
    }

    /**
     * session适用店铺查询接口
     * 待改进,如果多家店情况下，需要存储门店列表
     *
     * @param storeId
     */
    @SneakyThrows
    public void sessionScopeShop(Integer storeId) {
        DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
        if (dianpingTokenResult != null) {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", dianpingTokenResult.getDianpingAppkey());
            requestParam.put("timestamp", DateUtil.getCurrentDateTimeStr());
            requestParam.put("format", "json");
            requestParam.put("v", "1");
            requestParam.put("sign_method", "MD5");
            requestParam.put("session", dianpingTokenResult.getAccessToken());
            requestParam.put("bid", dianpingTokenResult.getBid());        // 验证签名，详情见签名生成说明文档
            requestParam.put("sign", SignUtil.signTopRequest(requestParam, dianpingTokenResult.getDianpingSecret(), "MD5"));
            String str = Request.Get("https://openapi.dianping.com/router/oauth/session/scope" + "?" + RequestUtil.mapToGetParam(requestParam))
                    .execute().returnContent().asString();
            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            if (code == 200) {
                String msg = jsonStr.getString("msg");
                JSONArray dataJsonArry = jsonStr.getJSONArray("data");
                for (int i = 0; i < dataJsonArry.size(); i++) {
                    JSONObject obj = (JSONObject) dataJsonArry.get(i);
                    String open_shop_uuid = obj.getString("open_shop_uuid");
                    dianpingTokenResult.setOpenShopUuid(open_shop_uuid);
                    redisUtils.set(AppConstants.SHOP_TOKEN_INFOR + storeId, dianpingTokenResult);
                    // 更新到对应的门店表中
                    MtStore mtStore = new MtStore();
                    mtStore.setId(storeId);
                    mtStore.setOpenShopUuid(open_shop_uuid);
                    LambdaQueryWrapper<MtStore> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(MtStore::getId, storeId);
                    mtStoreMapper.update(mtStore, wrapper1);

                    String shopname = obj.getString("shopname");
                    String branchname = obj.getString("branchname");
                    String shopaddress = obj.getString("shopaddress");
                    String cityname = obj.getString("cityname");
                    break;
                }
            }
        }

    }

    @SneakyThrows
    public void refreshSession(Integer storeId) {

/*      MtStore mtStore = storeService.queryStoreById(storeId);
        String appkey = mtStore.getDianpingAppkey();
        String secret = mtStore.getDianpingSecret();*/
        DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
        if (dianpingTokenResult != null) {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", dianpingTokenResult.getDianpingAppkey());
            requestParam.put("app_secret", dianpingTokenResult.getDianpingSecret());
            requestParam.put("grant_type", "refresh_token");
            requestParam.put("refresh_token", dianpingTokenResult.getRefreshToken());
            // 构造form
            Form form = Form.form();
            for (Map.Entry<String, String> entry : requestParam.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
            // 发起post请求
            String str = Request.Post("https://openapi.dianping.com/router/oauth/token/router/oauth/token")
                    .bodyForm(form.build())
                    .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded", "UTF-8").toString())
                    .execute().returnContent().asString();

            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            if (code == 200) {

                Integer remainRefreshCount = jsonStr.getInteger("remain_refresh_count"); // 剩余刷新次数
                // 如果刷新token数已用完，则设置提示标识，提醒重新授权绑定
                if (remainRefreshCount <= 0) {
                    redisUtils.set(AppConstants.SHOP_TOKEN_AUTH + storeId, 1);
                } else {
                    Long expiresIn = jsonStr.getLongValue("expires_in");
                    String accessToken = jsonStr.getString("access_token");
                    Date endDate = DateUtil.addDate(new Date(), Calendar.SECOND, expiresIn.intValue());
                    String refreshToken = jsonStr.getString("refresh_token");
                    String bid = jsonStr.getString("bid");
                    DianpingTokenResult dianpingTokenResultNew = new DianpingTokenResult();
                    dianpingTokenResultNew.setAccessToken(accessToken);
                    dianpingTokenResultNew.setEndDate(endDate);
                    dianpingTokenResultNew.setStoreId(storeId);
                    dianpingTokenResultNew.setRefreshToken(refreshToken);
                    dianpingTokenResultNew.setDianpingAppkey(dianpingTokenResult.getDianpingAppkey());
                    dianpingTokenResultNew.setDianpingSecret(dianpingTokenResult.getDianpingSecret());
                    dianpingTokenResultNew.setOpenShopUuid(dianpingTokenResult.getOpenShopUuid());
                    dianpingTokenResult.setBid(bid);
                    redisUtils.set(AppConstants.SHOP_TOKEN_INFOR + storeId, dianpingTokenResult);
                }
            }
        }
    }


    // 定时器每天判断token是否过期
    public void isTokenExpire() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", StatusEnum.ENABLED.getKey());
        List<MtStore> storeList = storeService.getMtStoreList(params);
        for (MtStore mtStore : storeList) {
            Integer storeId = mtStore.getId();
            DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
            if (dianpingTokenResult != null) {
                Date endDate = dianpingTokenResult.getEndDate();
                long now = (new Date()).getTime();
                long endTime = endDate.getTime();
                long timeDiff = (endTime - now) / 1000 / 60;
                if (timeDiff <= 0) {
                    // 刷新token
                    log.info("刷新token");
                    refreshSession(storeId);
                }
            }
        }

    }

    /**
     * 同步团购信息与在后台选择团购套餐Id对应卡券关联
     *
     * @param storeId
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    @Override
    public void syncGroupInfor(Integer storeId) throws IOException, NoSuchAlgorithmException {
        DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
        if (dianpingTokenResult != null) {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", dianpingTokenResult.getDianpingAppkey());
            requestParam.put("timestamp", DateUtil.getCurrentDateTimeStr());
            requestParam.put("format", "json");
            requestParam.put("v", "1");
            requestParam.put("sign_method", "MD5");
            // 调试中暂时注释
            requestParam.put("session", dianpingTokenResult.getAccessToken());
            requestParam.put("open_shop_uuid", dianpingTokenResult.getOpenShopUuid());
//            requestParam.put("session", "73635faedd68bbdf3fed2594b9b78c4ba21b7bed");
//            requestParam.put("open_shop_uuid", "03353631c0d0d08b4679ff097e6b7df2");
            requestParam.put("offset", "1");
            requestParam.put("limit", "100");
            // 验证签名，详情见签名生成说明文档
            requestParam.put("sign", SignUtil.signTopRequest(requestParam, dianpingTokenResult.getDianpingSecret(), "MD5"));
            // 发起get请求
            String str = Request.Get("https://openapi.dianping.com/tuangou/deal/queryshopdeal"
                    + "?"
                    + RequestUtil.mapToGetParam(requestParam))
                    .execute().returnContent().asString();
            log.info("syncGroupInfor:" + str);
            //syncGroupInfor:{"code":200,"msg":"success","data":[{"deal_id":993507556,"dealgroup_id":794479306,
            // "begin_date":"2022-09-20 11:34","end_date":"2023-09-20 00:00","title":"60分钟足部足疗",
            // "price":1.0,"marketprice":100.0,"receipt_begin_date":"2023-06-06 10:28",
            // "receipt_end_date":"2023-09-04 23:59","sale_status":2,"deal_type":"1"},
            // {"deal_id":915471790,"dealgroup_id":763617779,"begin_date":"2022-04-15 15:12","end_date":"2023-07-14 00:00",
            // "title":"多个子项目的团购","price":2.0,"marketprice":3.0,"receipt_begin_date":"2023-06-06 10:28",
            // "receipt_end_date":"2023-09-04 23:59","sale_status":2,"deal_type":"1"},
            // {"deal_id":889380278,"dealgroup_id":749780420,"begin_date":"2022-06-17 10:30","end_date":"2023-06-17 00:00",
            // "title":"只有商家优惠测试团购","price":12.0,"marketprice":15.0,"receipt_begin_date":"2023-06-06 10:28","
            // receipt_end_date":"2023-09-04 23:59","sale_status":2,"deal_type":"1"},{"deal_id":943017524,
            // "dealgroup_id":776306224,"begin_date":"2022-06-22 15:39","end_date":"2023-06-22 00:00","title":"60分钟足部足疗",
            // "price":1.0,"marketprice":120.0,"receipt_begin_date":"2023-06-06 10:28","receipt_end_date":"2023-09-04 23:59",
            // "sale_status":2,"deal_type":"1"},{"deal_id":915587336,"dealgroup_id":763649164,"begin_date":"2022-04-15 15:17",
            // "end_date":"2024-04-17 00:00","title":"代金券","price":1.0,"marketprice":1.5,"receipt_begin_date":"2023-06-06 10:28",
            // "receipt_end_date":"2023-09-04 23:59","sale_status":2,"deal_type":"2"},{"deal_id":986640985,"dealgroup_id":792387671,
            // "begin_date":"2022-09-07 15:25","end_date":"2023-09-07 00:00","title":"桌面游戏测试","price":20.0,"marketprice":70.0,
            // "receipt_begin_date":"2023-06-06 10:28","receipt_end_date":"2023-09-04 23:59","sale_status":2,"deal_type":"1"},
            // {"deal_id":942850671,"dealgroup_id":776239258,"begin_date":"2022-06-22 11:36","end_date":"2023-06-22 00:00",
            // "title":"代金券","price":1.0,"marketprice":2.0,"receipt_begin_date":"2023-06-06 10:28",
            // "receipt_end_date":"2023-09-04 23:59","sale_status":2,"deal_type":"2"}]}

            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            if (code == 200) {
                String msg = jsonStr.getString("msg");
                JSONArray dataJsonArry = jsonStr.getJSONArray("data");
                for (int i = 0; i < dataJsonArry.size(); i++) {
                    JSONObject obj = (JSONObject) dataJsonArry.get(i);
                    Long deal_id = obj.getLong("deal_id");
                    Long dealgroup_id = obj.getLong("dealgroup_id");
                    String begin_date = obj.getString("begin_date");
                    String end_date = obj.getString("end_date");
                    String title = obj.getString("title");
                    Double price = obj.getDouble("price");
                    Double marketprice = obj.getDouble("marketprice");
                    String receipt_begin_date = obj.getString("receipt_begin_date");
                    String receipt_end_date = obj.getString("receipt_end_date");
                    Integer sale_status = obj.getInteger("sale_status");
                    String deal_type = obj.getString("deal_type"); // 1-团购套餐，2-代金券
                    // 先添加团购记录，然后在后台，手动关联卡券或优惠券,如果存在，则更新
                    MtDianpingGroup mtDianpingGroup = new MtDianpingGroup();
                    mtDianpingGroup.setDealId(deal_id.intValue());
                    mtDianpingGroup.setDealgroupId(dealgroup_id.intValue());
                    mtDianpingGroup.setBeginDate(begin_date);
                    mtDianpingGroup.setEndDate(end_date);
                    mtDianpingGroup.setTitle(title);
                    mtDianpingGroup.setPrice(BigDecimal.valueOf(price));
                    mtDianpingGroup.setMarketprice(BigDecimal.valueOf(marketprice));
                    mtDianpingGroup.setReceiptBeginDate(receipt_begin_date);
                    mtDianpingGroup.setReceiptEndDate(receipt_end_date);
                    mtDianpingGroup.setSaleStatus(sale_status);
                    mtDianpingGroup.setDealType(Integer.valueOf(deal_type));
                    mtDianpingGroup.setStoreId(storeId);
                    saveDianpingGroup(mtDianpingGroup);
                }
            }
        }
    }

    public void saveDianpingGroup(MtDianpingGroup mtDianpingGroup) {
        LambdaQueryWrapper<MtDianpingGroup> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(MtDianpingGroup::getDealId, mtDianpingGroup.getDealId());
        MtDianpingGroup temp = mtDianpingGroupMapper.selectOne(lambdaQueryWrapper);
        if (temp == null) {
            mtDianpingGroupService.save(mtDianpingGroup);
        } else {
            mtDianpingGroupService.updateById(mtDianpingGroup);
        }
    }


    // 输码验券校验
    @SneakyThrows
    @Override
    public DianpingPrepareResult prepare(Integer storeId, String receiptCode) {
        DianpingPrepareResult dianpingPrepareResult = new DianpingPrepareResult();
        DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
        if (dianpingTokenResult != null) {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", dianpingTokenResult.getDianpingAppkey());
            requestParam.put("timestamp", DateUtil.getCurrentDateTimeStr());
            requestParam.put("format", "json");
            requestParam.put("v", "1");
            requestParam.put("sign_method", "MD5");
            // 调试中暂时注释
            requestParam.put("session", dianpingTokenResult.getAccessToken());
            requestParam.put("open_shop_uuid", dianpingTokenResult.getOpenShopUuid());
//            requestParam.put("session", "73635faedd68bbdf3fed2594b9b78c4ba21b7bed");
//            requestParam.put("open_shop_uuid", "03353631c0d0d08b4679ff097e6b7df2");
            requestParam.put("receipt_code", receiptCode);
            // 验证签名，详情见签名生成说明文档
            try {
                requestParam.put("sign", SignUtil.signTopRequest(requestParam, dianpingTokenResult.getDianpingSecret(), AppConstants.SIGN_METHOD_MD5));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            Form form = Form.form();
            for (Map.Entry<String, String> entry : requestParam.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }

            // 发起post请求
            String str = Request.Post("https://openapi.dianping.com/router/tuangou/receipt/prepare")
                    .bodyForm(form.build())
                    .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded", "UTF-8").toString())
                    .execute().returnContent().asString();

            log.info("prepare:" + str);
            //prepare:{"code":200,"msg":"验证校验通过",
            // "data":{"count":1,"receipt_code":"0374884627","deal_id":943017524,"dealgroup_id":776306224,
            // "deal_title":"60分钟足部足疗","deal_price":1.0,"deal_marketprice":120.0,"mobile":"150****2607",
            // "product_type":null,"product_item_id":null,"biz_type":0,
            // "payment_detail":[{"payment_detail_id":"491795400037731897374YD50101","amount":1.00,"amount_type":10}],
            // "receipt_info_map":null,"receiptEndDate":1693843199000}}

            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            if (code == 200) {
                JSONObject dataJsonObject = jsonStr.getJSONObject("data");
                Integer count = dataJsonObject.getInteger("count");
                String receiptCode1 = dataJsonObject.getString("receipt_code");
                Long dealId = dataJsonObject.getLong("deal_id");
                Long dealgroupId = dataJsonObject.getLong("dealgroup_id");
                String dealTitle = dataJsonObject.getString("deal_title");
                Double deal_price = dataJsonObject.getDouble("deal_price");
                Double deal_marketprice = dataJsonObject.getDouble("deal_marketprice");
                Integer biz_type = dataJsonObject.getInteger("biz_type");
                Date receiptEndDate = dataJsonObject.getDate("receiptEndDate");
                String mobile = dataJsonObject.getString("mobile");
                //dianpingPrepareResult = new DianpingPrepareResult();
                dianpingPrepareResult.setCount(count);
                dianpingPrepareResult.setReceiptCode(receiptCode1);
                dianpingPrepareResult.setDealId(dealId);
                dianpingPrepareResult.setDealgroupId(dealgroupId);
                dianpingPrepareResult.setDealTitle(dealTitle);
                dianpingPrepareResult.setDealPrice(deal_price);
                dianpingPrepareResult.setDealMarketprice(deal_marketprice);
                dianpingPrepareResult.setBizType(biz_type);
                dianpingPrepareResult.setReceiptEndDate(receiptEndDate);
                dianpingPrepareResult.setMobile(mobile);
                return dianpingPrepareResult;

            }

        }
        return dianpingPrepareResult;
    }

    /**
     * 扫码验券校验
     *
     * @param qrCode
     */
    @SneakyThrows
    @Override
    public DianpingPrepareResult scanPrepare(Integer storeId, String qrCode) {
        DianpingPrepareResult dianpingPrepareResult = new DianpingPrepareResult();
        DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
        if (dianpingTokenResult != null) {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", dianpingTokenResult.getDianpingAppkey());
            requestParam.put("timestamp", DateUtil.getCurrentDateTimeStr());
            requestParam.put("format", "json");
            requestParam.put("v", "1");
            requestParam.put("sign_method", "MD5");
            // 调试中暂时注释
            //requestParam.put("session", dianpingTokenResult.getAccessToken());
            //requestParam.put("open_shop_uuid", dianpingTokenResult.getOpenShopUuid());
            requestParam.put("session", "73635faedd68bbdf3fed2594b9b78c4ba21b7bed");
            requestParam.put("qr_code", qrCode);
            //prepare:{"code":200,"msg":"验证校验通过",
            // "data":{"count":1,"receipt_code":"0374884627","deal_id":943017524,"dealgroup_id":776306224,
            // "deal_title":"60分钟足部足疗","deal_price":1.0,"deal_marketprice":120.0,"mobile":"150****2607",
            // "product_type":null,"product_item_id":null,"biz_type":0,
            // "payment_detail":[{"payment_detail_id":"491795400037731897374YD50101","amount":1.00,"amount_type":10}],
            // "receipt_info_map":null,"receiptEndDate":1693843199000}}
            // 验证签名，详情见签名生成说明文档
            requestParam.put("sign", SignUtil.signTopRequest(requestParam, dianpingTokenResult.getDianpingSecret(), "MD5"));
            // 构造form
            Form form = Form.form();
            for (Map.Entry<String, String> entry : requestParam.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
            // 发起post请求
            String str = Request.Post("https://openapi.dianping.com/router/tuangou/receipt/scanprepare")
                    .bodyForm(form.build())
                    .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded", "UTF-8").toString())
                    .execute().returnContent().asString();

            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            if (code == 200) {
                JSONObject dataJsonObject = jsonStr.getJSONObject("data");
                Integer count = dataJsonObject.getInteger("count");
                String receiptCode1 = dataJsonObject.getString("receipt_code");
                Long dealId = dataJsonObject.getLong("deal_id");
                Long dealgroupId = dataJsonObject.getLong("dealgroup_id");
                String dealTitle = dataJsonObject.getString("deal_title");
                Double deal_price = dataJsonObject.getDouble("deal_price");
                Double deal_marketprice = dataJsonObject.getDouble("deal_marketprice");
                Integer biz_type = dataJsonObject.getInteger("biz_type");
/*                Date receiptEndDate = jsonStr.getDate("receiptEndDate");
                String mobile = jsonStr.getString("mobile");*/
                //dianpingPrepareResult = new DianpingPrepareResult();
                dianpingPrepareResult.setCount(count);
                dianpingPrepareResult.setReceiptCode(receiptCode1);
                dianpingPrepareResult.setDealId(dealId);
                dianpingPrepareResult.setDealgroupId(dealgroupId);
                dianpingPrepareResult.setDealTitle(dealTitle);
                dianpingPrepareResult.setDealPrice(deal_price);
                dianpingPrepareResult.setDealMarketprice(deal_marketprice);
                dianpingPrepareResult.setBizType(biz_type);
                return dianpingPrepareResult;

            }
        }
        return dianpingPrepareResult;
    }

    // 团购验券、生成用户对应的卡券或优惠券
    @SneakyThrows
    @Override
    public DianpingResult consume(Integer userId, Integer storeId, String receiptCode, Integer count, String random) {
        DianpingTokenResult dianpingTokenResult = (DianpingTokenResult) redisUtils.get(AppConstants.SHOP_TOKEN_INFOR + storeId);
        //Integer requestid = (Integer) redisUtils.get(AppConstants.SHOP_REQUESTID);
        //requestid = requestid+1;
        //RandomUtil.getRandom(5);
        DianpingResult dianpingResult = new DianpingResult();

        if (dianpingTokenResult != null) {

            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("app_key", dianpingTokenResult.getDianpingAppkey());
            requestParam.put("timestamp", DateUtil.getCurrentDateTimeStr());
            requestParam.put("format", "json");
            requestParam.put("v", "1");
            requestParam.put("sign_method", "MD5");
            // 调试中暂时注释
            requestParam.put("session", dianpingTokenResult.getAccessToken());
            requestParam.put("open_shop_uuid", dianpingTokenResult.getOpenShopUuid());
//            requestParam.put("session", "73635faedd68bbdf3fed2594b9b78c4ba21b7bed");
//            requestParam.put("open_shop_uuid", "03353631c0d0d08b4679ff097e6b7df2");
            requestParam.put("receipt_code", receiptCode);
            requestParam.put("requestid", random);
            requestParam.put("count", count + "");
            requestParam.put("app_shop_account", storeId + "");
            requestParam.put("app_shop_accountname", storeId + "");
            //验证签名，详情见签名生成说明文档
            requestParam.put("sign", SignUtil.signTopRequest(requestParam, dianpingTokenResult.getDianpingSecret(), "MD5"));
            //构造form
            Form form = Form.form();
            for (Map.Entry<String, String> entry : requestParam.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
            // 发起post请求
            String str = Request.Post("https://openapi.dianping.com/router/tuangou/receipt/consume")
                    .bodyForm(form.build())
                    .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded", "UTF-8").toString())
                    .execute().returnContent().asString();

            log.info("consume:" + str);
            //consume:{"code":200,"msg":"验证成功",
            // "data":[{"order_id":"168602465845040040963397","receipt_code":"0374884627",
            // "app_shop_id":null,"open_shop_uuid":"03353631c0d0d08b4679ff097e6b7df2",
            // "deal_id":943017524,"dealgroup_id":776306224,"deal_title":"60分钟足部足疗",
            // "product_type":null,"product_item_id":null,"deal_price":1.0,"deal_marketprice":120.0,
            // "mobile":"150****2607","biz_type":0,
            // "payment_detail":[{"payment_detail_id":"491795400037731897374YD50101","amount":1.00,"amount_type":10}],
            // "receiptEndDate":1693843199000,"disclose_mobile_no":0}]}

            JSONObject jsonStr = JSONObject.parseObject(str);
            Integer code = jsonStr.getInteger("code");
            String msg = jsonStr.getString("msg");
            dianpingResult.setCode(code);
            dianpingResult.setMsg(msg);
            //redisUtils.set(AppConstants.SHOP_REQUESTID,requestid);
            if (code == 200) {

                // 根据返回的套餐id,获取关联的卡券或优惠券记录
                JSONArray jsonArray = jsonStr.getJSONArray("data");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    Long dealId = jsonObject.getLong("deal_id");
                    String order_id = jsonObject.getString("order_id");
                    LambdaQueryWrapper<MtCoupon> lambdaQueryWrapper = Wrappers.lambdaQuery();
                    lambdaQueryWrapper.eq(MtCoupon::getDealId, dealId);
                    List<MtCoupon> dataList = mtCouponMapper.selectList(lambdaQueryWrapper);
                    if (dataList != null && dataList.size() > 0) {
                        MtCoupon mtCoupon = dataList.get(0);
                        // 用户卡券(小时卡、次数卡)购买订单
                        // 生成用户对应的卡券
                        if (mtCoupon.getType().equals(CouponTypeEnum.HOUR.getKey())
                                || mtCoupon.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
                            Map<String, Object> param = new HashMap<>();
                            param.put("couponId", mtCoupon.getId());
                            param.put("userId", userId);
                            param.put("orderId", order_id);
                            param.put("storeId", storeId);
                            userCouponService.userBuyConpon(param);
                            // 生成用户对应的优惠券
                        } else if (mtCoupon.getType().equals(CouponTypeEnum.COUPON.getKey())) {
                            userCouponService.buyCouponItem(order_id, mtCoupon.getId(), userId, storeId,"D");
                        }
                    }
                }
            }
        }
        return dianpingResult;
    }

    /**
     * 根据本地门店Id,获取点评美团同步的团购套餐列表
     *
     * @param mtDianpingGroup
     * @return
     */
    @Override
    public List<MtDianpingGroup> getDianpingGroupList(MtDianpingGroup mtDianpingGroup, List<Integer> storeIdList) {
        LambdaQueryWrapper<MtDianpingGroup> lambdaQueryWrapper = Wrappers.lambdaQuery();
//        lambdaQueryWrapper.eq(MtDianpingGroup::getStoreId, mtDianpingGroup.getStoreId());
        if (storeIdList != null) {
            lambdaQueryWrapper.in(MtDianpingGroup::getStoreId, storeIdList);
        }
        List<MtDianpingGroup> list = mtDianpingGroupMapper.selectList(lambdaQueryWrapper);
        return list;
    }

}
